
import string
import os
import re
from pepe.glib import *
from basic import *


def is_compressed_file(f):
    """Decide whether it is a compressed file or not """
    extensions = [".zip", ".gz", ".tar", ".rar", ".tar", ".z"]
    if os.path.splitext(f)[1].lower in extensions:
        return True
    else:
        return False


def check_7z_log(f):
    """Check 7zip log file and report successful extraction """
    if os.path.exists(f):
        data = open(f, 'r').read()
        if re.search('Everything is Ok', data):
            return True
    return False
        
    if 0: # testing procedure - ok
        # checking nonexistent file
        print check_7z_log(r'.\logs\20110201192114184000_LHGL Data.zip.extract')
        # checking existent and OK log file
        print check_7z_log(r'.\logs\20110201192114184000_LHGL Data.zip.extract.log')


def file_extract(f, outDir, logDir, rmZip=False):
    """Extraction of compressed file
    
    f       - file with full path to be extracted
    tempDir - directory where to extract given file
    logDir  - log directory where to store log files
    rmZip   - remove compressed source file after sucessfull extraction

    """
    #Use this if there are any .rar files
    #commandString = "7z x -r -y -pHP2DT -o\"" + dataDir + "\\dce\\\"* \"" + os.path.join(dataD
    #ir, f) + "\" -- > \""+ logDir + str(counter) + "_" + f + ".extract.log\""
    
    # create log directory if des not exists
    if not os.path.exists(logDir):
        os.mkdir(logDir)
    
    fname = string.split(f, '\x5C')[-1]
    
    dt = dtnow()
    
    # use this if there are any .tar files
    ca = r"""C:\aft\pmfs\7za920\7za x -r -y -pHP2DT -o""" 

    cb = "\"%s*_xXx%s\" \"%s\" -- > \"%s%s_%s.extract.log\"" % (outDir, dtnow(), f, logDir, dt, fname)
    # do not use 'folders timestamping for tar files
    #    because it creates the same exrtacted directory 
    #    so many times as the number of files in extracted directory
    if os.path.splitext(f)[1].lower() == '.tar':
        cb = "\"%s*\" \"%s\" -- > \"%s%s_%s.extract.log\"" % (outDir, f, logDir, dt, fname)

    #print ca + cb
    os.system(ca + cb)

    logfile = "%s%s_%s.extract.log" % (logDir, dt, fname)
    
    # remove zip file if extraction was sucessfull
    #if rmZip == True and check_7z_log(logfile) == True: 
    # remove even if unsuccessfuls
    if rmZip == True: os.remove(f)
    
    #delete dce
    #if os.path.exists(os.path.join(tempDir, "ext")):
    #	shutil.rmtree(os.path.join(tempDir, "dce"))
    return logfile

    if 0: # test procedure - ok
        # A:\SAP FI1\2010-11-11
        simpleExtract(f=r'A:\SAP FUSION\2010-10-19\original\R01_VBRK_AT00_2007to2010.dmp.gz', 
                      outDir=r'D:\viktor' + '\x5C', 
                      logDir=r'D:\viktor\logs' + '\x5C')


def dir_recursive_extract(filesDir, logDir, zipExt, removeSource=False):
    """Recursive extract of compressed files in directory

    f       - file with full path to be extracted
    outDir  - directory where to extract given file
    logDir  - log directory where to store log files
    zipExt  - extensions that indicate compressed files

    """
    while look_for_extension(filesDir, extensions=zipExt):

        # get list of files to be processed
        files = files_list(filesDir)
        
        # process files
        for f in files:
            if os.path.splitext(f)[1] in zipExt:
                #print f
                outDir = string.join(string.split(f, '\x5C')[:-1], '\x5C') + '\x5C'
                file_extract(f, outDir, logDir, rmZip=True)

    if 0: # test procedure - ok

        fd = r'D:\viktor' + '\x5C'
        ld = os.getcwd() + "\\logs" + '\x5C'
        ze = [".zip", ".gz", ".tar", ".rar", ".tar", ".Z"]
    
        file_extract(  f=r'A:\SAP LH1\2010-07-28\original\LHGL Data.zip',
                      outDir=fd,
                      logDir=ld)
        dir_recursive_extract(filesDir=fd, logDir=ld, zipExt=ze)
